package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.common.minio.MinIOFileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import com.heima.utils.common.JsonUtils;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    @Autowired
    private ApArticleContentMapper apArticleContentMapper;
    @Autowired
    private Configuration configuration;
    @Autowired
    private MinIOFileStorageService storageService;
    @Autowired
    private ApArticleMapper apArticleMapper;

    @Override
    public void createStaticPage(Long id) {
        try {
            //根据文章ID查询其文章内容（动）
            QueryWrapper<ApArticleContent> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("article_id",id);
            ApArticleContent apArticleContent = apArticleContentMapper.selectOne(queryWrapper);

            if(apArticleContent!=null && StringUtils.isNotEmpty(apArticleContent.getContent())){
                //读取文章详情页模板(article.ftl)（静）
                Template template = configuration.getTemplate("article.ftl");

                //准备Map集合用于给模板页面填充数据
                List<Map> list = JsonUtils.toList(apArticleContent.getContent(),Map.class);
                Map<String,Object> resultMap = new HashMap<>();
                resultMap.put("content",list);

                //利用Freemarker技术生成文章静态页面
                StringWriter writer = new StringWriter();//缓存字符流
                template.process(resultMap,writer);

                //把文章的静态页面存入MinIO，以方便用户后期访问
                ByteArrayInputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());//字符转换字节
                String url = storageService.uploadHtmlFile("", id + ".html", inputStream);

                //修改文章的静态页面路径
                ApArticle apArticle = new ApArticle();
                apArticle.setId(id);
                apArticle.setStaticUrl(url);
                apArticleMapper.updateById(apArticle);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("静态页面生成失败："+e);
        }
    }
}
